package com.itlong.cloud.operate.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.itlong.cloud.POJO.DTO.operate.OperateProductTypeGetPageDTO;
import com.itlong.cloud.POJO.DTO.operate.OperateProductTypeSaveDTO;
import com.itlong.cloud.POJO.PO.ProductTypePO;
import com.itlong.cloud.POJO.VO.operate.OperateProductTypeDetailVO;
import com.itlong.cloud.POJO.VO.operate.OperateProductTypeVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.constants.RabbitMQConstant;
import com.itlong.cloud.enumerate.DataStatusEnum;
import com.itlong.cloud.enumerate.PropertyEquipTypeEnum;
import com.itlong.cloud.operate.dao.IOperateProductTypeDao;
import com.itlong.cloud.operate.service.IOperateProductTypeService;
import com.itlong.cloud.rabbitmq.config.MessageSender;
import com.itlong.cloud.utils.data.handler.SqlUtil;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.random.LogicIdUtil;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <desc>
 *      产品型号管理接口实现
 * </desc>
 *
 * @createDate 2017-10-13.
 */
@Service
public class OperateProductTypeServiceImpl implements IOperateProductTypeService {

    @Autowired
    private IOperateProductTypeDao iOperateProductTypeDao;

    //消息队列
    @Autowired
    private MessageSender messageSender;


    /**
     * <desc>
     * 判断产品型号存在性
     * <desc/>
     *
     * @param typePid 产品型号Pid
     * @return 同型号Pid的个数
     * @author Chunjian.G
     * @createDate 2017-10-26
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Integer checkProductExist(String typePid) throws Exception {
        return iOperateProductTypeDao.checkProductExist(typePid);
    }

    /**
     * <desc>
     * 添加单个产品型号
     * <desc/>
     *
     * @param saveDTO 新增型号信息
     * @return
     * @author Chunjian.G
     * @createDate 2017-10-13
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer saveProductType(OperateProductTypeSaveDTO saveDTO) throws Exception {
        //梯控、门禁 的PID 自动生成
        if (!PropertyEquipTypeEnum.CLOUD_INTERCOM.getType().equals(saveDTO.getDeviceKind())){
            saveDTO.setTypePid(LogicIdUtil.bussinessId());
        }
        ProductTypePO typePO = new ProductTypePO();
        BeanUtils.copyProperties(saveDTO, typePO);
        typePO.setStatus(DataStatusEnum.NORMAL.getType());
        Date createTime = new Date();
        typePO.setCreateTime(createTime);
        typePO.setUpdateTime(createTime);
        Map<String, Object> params = SqlUtil.durableData(typePO, PlatformConstants.TABLE_SAVE);
        Integer result = iOperateProductTypeDao.save(params);
        //添加电梯产品，发送新增产品型号
        if((result>0)&&PropertyEquipTypeEnum.CLOUD_ELEVATOR.getType().equals(saveDTO.getDeviceKind())){
            JSONObject datajs = new JSONObject();
            datajs.put("data",JSONObject.toJSON(typePO));
            messageSender.send(RabbitMQConstant.RABBITMQ_PRODUCT_QUEUE, JsonUtil.toJSON(datajs),
                    RabbitMQConstant.RABBITMQ_PRODUCT_EXCHANGE,
                    RabbitMQConstant.RABBITMQ_PRODUCT_KEY);
        }
        return 1;
    }

    /**
     * <desc>
     * 根据型号ID更新产品型号
     * <desc/>
     *
     * @param updateDTO 型号更新信息
     * @return
     * @author Chunjian.G
     * @createDate 2017-10-13
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer updateProductType(OperateProductTypeSaveDTO updateDTO) throws Exception {

        ProductTypePO typePO = new ProductTypePO();
        BeanUtils.copyProperties(updateDTO, typePO);
        typePO.setCreateTime(null);//不允许更新创建时间
        typePO.setUpdateTime(new Date());
        Map<String, Object> params = SqlUtil.durableData(typePO, PlatformConstants.TABLE_UPDATE);
        Integer result = iOperateProductTypeDao.update(params);
        //云电梯更新查询iotProductKey
        if(PropertyEquipTypeEnum.CLOUD_ELEVATOR.getType() == updateDTO.getDeviceKind()){
            String iotProductKey = iOperateProductTypeDao.getIotProductKey(updateDTO.getTypePid());
            typePO.setIotProductKey(iotProductKey);
        }
        if((result>0)&&PropertyEquipTypeEnum.CLOUD_ELEVATOR.getType().equals(updateDTO.getDeviceKind())){
            JSONObject datajs = new JSONObject();
            datajs.put("data",JSONObject.toJSON(typePO));
            messageSender.send(RabbitMQConstant.RABBITMQ_PRODUCT_QUEUE, JsonUtil.toJSON(datajs),
                    RabbitMQConstant.RABBITMQ_PRODUCT_EXCHANGE,
                    RabbitMQConstant.RABBITMQ_PRODUCT_KEY);
        }
        return 1;
    }

    /**
     * <desc>
     *      查询是否有项目关联设备类型
     * <desc/>
     *
     * @param typePid 型号ID
     * @return
     * @author Qiang.S
     * @createDate 2018-07-25
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer getProductCount(String typePid) throws Exception {

        return iOperateProductTypeDao.getProductCount(typePid);
    }


    /**
     * <desc>
     * 删除设备型号
     * <desc/>
     *
     * @param typePid 型号ID列表
     * @return
     * @author Chunjian.G
     * @createDate 2017-10-13
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer removeProductType(String typePid) throws Exception {

        return iOperateProductTypeDao.removeBatch(typePid);
    }

    /**
     * <desc>
     * 分页查询产品型号
     * <desc/>
     *
     * @param pageDTO 查询条件DTO
     * @return
     * @author Chunjian.G
     * @createDate 2017-10-13
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Page<OperateProductTypeVO> getPage(OperateProductTypeGetPageDTO pageDTO) throws Exception {
        //分页对象
        Page<OperateProductTypeVO> page = new Page<>();
        //将DTO转换为Map
        Map<String, Object> params = SqlUtil.convertBeanToMapParams(pageDTO, page);
        //查询
        List<OperateProductTypeVO> typeVOS = iOperateProductTypeDao.getSimplePage(params);
        for (OperateProductTypeVO operateProductTypeVO:typeVOS) {
            if (operateProductTypeVO.getServerKey() != null && !"".equals(operateProductTypeVO.getServerKey())) {
                operateProductTypeVO.setServerKey(Base64.encode(operateProductTypeVO.getServerKey().getBytes()));
            }
            if (operateProductTypeVO.getSignPubKey() != null && !"".equals(operateProductTypeVO.getSignPubKey())) {
                operateProductTypeVO.setSignPubKey(Base64.encode(operateProductTypeVO.getSignPubKey().getBytes()));
            }
            if (operateProductTypeVO.getSignSecretKey() != null && !"".equals(operateProductTypeVO.getSignSecretKey())) {
                operateProductTypeVO.setSignSecretKey(Base64.encode(operateProductTypeVO.getSignSecretKey().getBytes()));
            }
        }
        Integer count = iOperateProductTypeDao.getCount(params);
        //填充返回数据集
        page.setRows(typeVOS, count);
        return page;
    }

    /**
     * <desc>
     * 获取单个产品型号详情
     * <desc/>
     *
     * @param typePid 型号ID
     * @return
     * @author Chunjian.G
     * @createDate 2017-10-13
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public OperateProductTypeDetailVO getDetail(String typePid) throws Exception {
        return iOperateProductTypeDao.getDetail(typePid);
    }

    /**
     * <desc>
     *      检测是否存在云电梯的产品。
     * <desc/>
     *
     * @param deviceType 设备类型
     * @param typeCode 型号代号
     * @return
     * @author shengen.T
     * @createDate 2018-04-17
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Integer checkCloudElevatorExist(Integer deviceType,String typeCode) throws Exception{
        return iOperateProductTypeDao.checkCloudElevatorExist(deviceType,typeCode);
    }
}
